<template>
    <div class="login-page">
    <el-container class="login-container">
      <el-card class="login-card">
        <template #header>
          <div class="card-header">
            <span>{{ isRegister ? '注册' : (isForgotPassword ? '找回密码' : '登录') }}</span>
          </div>
        </template>

        <!-- 登录表单 -->
        <el-form
          v-if="!isRegister && !isForgotPassword"
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-width="0"
        >
          <!-- 登录方式切换 -->
          <el-form-item>
            <el-radio-group v-model="loginType" size="large">
              <el-radio-button label="account">手机号密码登录</el-radio-button>
              <el-radio-button label="phone">手机号短信登录</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <!-- 账号密码登录 -->
          <template v-if="loginType === 'account'">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.phone"
                placeholder="手机号"
                prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="Picture"
              >
                <template #append>
                  <img 
                    :src="captchaUrl" 
                    class="captcha-image" 
                    @click="refreshCaptcha"
                    alt="点击刷新验证码"
                  />
                </template>
              </el-input>
            </el-form-item>
          </template>

          <!-- 手机号登录 -->
          <template v-else>
            <el-form-item prop="phone">
              <el-input
                v-model="loginForm.phone"
                placeholder="手机号"
                prefix-icon="Iphone"
              />
            </el-form-item>
            <el-form-item prop="smsCode">
              <el-input
                v-model="loginForm.smsCode"
                placeholder="验证码"
                prefix-icon="Message"
              >
                <template #append>
                  <el-button 
                    :disabled="smsCodeTimer > 0" 
                    @click="handleSendSmsCode('login')"
                  >
                    {{ smsCodeTimer > 0 ? `${smsCodeTimer}s后重新获取` : '获取验证码' }}
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item prop="captcha">
              <el-input
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                prefix-icon="Picture"
              >
                <template #append>
                  <img 
                    :src="captchaUrl" 
                    class="captcha-image" 
                    @click="refreshCaptcha"
                    alt="点击刷新验证码"
                  />
                </template>
              </el-input>
            </el-form-item>
          </template>

          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              class="login-btn"
              @click="handleLogin"
            >
              登录注册
            </el-button>
          </el-form-item>

          <div class="form-footer">
            <el-link type="primary" @click="switchToForgotPassword">忘记密码？</el-link>
            <el-link type="primary" @click="switchToRegister">注册</el-link>
          </div>
        </el-form>

        <!-- 注册表单 -->
        <el-form
          v-if="isRegister"
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="0"
        >
          <el-form-item prop="name">
            <el-input
              v-model="registerForm.name"
              placeholder="姓名"
              prefix-icon="User"
            />
          </el-form-item>
          <el-form-item prop="phone">
            <el-input
              v-model="registerForm.phone"
              placeholder="手机号"
              prefix-icon="Iphone"
            />
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              v-model="registerForm.email"
              placeholder="邮箱"
              prefix-icon="Message"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              v-model="registerForm.password"
              type="password"
              placeholder="密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="registerForm.confirmPassword"
              type="password"
              placeholder="确认密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="smsCode">
            <el-input
              v-model="registerForm.smsCode"
              placeholder="验证码"
              prefix-icon="Message"
            >
              <template #append>
                <el-button 
                  :disabled="smsCodeTimer > 0" 
                  @click="handleSendSmsCode('register')"
                >
                  {{ smsCodeTimer > 0 ? `${smsCodeTimer}s后重新获取` : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              v-model="registerForm.captcha"
              placeholder="请输入验证码"
              prefix-icon="Picture"
            >
              <template #append>
                <img 
                  :src="captchaUrl" 
                  class="captcha-image" 
                  @click="refreshCaptcha"
                  alt="点击刷新验证码"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              class="login-btn"
              @click="handleRegister"
            >
              注册
            </el-button>
          </el-form-item>
          <div class="form-footer">
            <el-link type="primary" @click="switchToLogin">返回登录</el-link>
          </div>
        </el-form>

        <!-- 找回密码表单 -->
        <el-form
          v-if="isForgotPassword"
          ref="forgotPasswordFormRef"
          :model="forgotPasswordForm"
          :rules="forgotPasswordRules"
          label-width="0"
        >
          <el-form-item prop="phone">
            <el-input
              v-model="forgotPasswordForm.phone"
              placeholder="手机号"
              prefix-icon="Iphone"
            />
          </el-form-item>
          <el-form-item prop="smsCode">
            <el-input
              v-model="forgotPasswordForm.smsCode"
              placeholder="验证码"
              prefix-icon="Message"
            >
              <template #append>
                <el-button 
                  :disabled="smsCodeTimer > 0" 
                  @click="handleSendSmsCode('forgot')"
                >
                  {{ smsCodeTimer > 0 ? `${smsCodeTimer}s后重新获取` : '获取验证码' }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="newPassword">
            <el-input
              v-model="forgotPasswordForm.newPassword"
              type="password"
              placeholder="新密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="confirmPassword">
            <el-input
              v-model="forgotPasswordForm.confirmPassword"
              type="password"
              placeholder="确认新密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item prop="captcha">
            <el-input
              v-model="forgotPasswordForm.captcha"
              placeholder="请输入验证码"
              prefix-icon="Picture"
            >
              <template #append>
                <img 
                  :src="captchaUrl" 
                  class="captcha-image" 
                  @click="refreshCaptcha"
                  alt="点击刷新验证码"
                />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :loading="loading"
              class="login-btn"
              @click="handleResetPassword"
            >
              重置密码
            </el-button>
          </el-form-item>
          <div class="form-footer">
            <el-link type="primary" @click="switchToLogin">返回登录</el-link>
          </div>
        </el-form>
      </el-card>
    </el-container>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock, Iphone, Message } from '@element-plus/icons-vue'
import { 
  getCaptcha, 
  sendCode, 
  login,
  register,
  resetPassword,
  type LoginRequest,
  type SendSmsCodeRequest,
  type RegisterRequest,
  type ResetPasswordRequest,
  type ApiResponse
} from '@/api/auth'


const router = useRouter()
const loading = ref(false)
const loginFormRef = ref<FormInstance>()
const registerFormRef = ref<FormInstance>()
const forgotPasswordFormRef = ref<FormInstance>()

// 登录方式
const loginType = ref('account')

// 表单显示控制
const isRegister = ref(false)
const isForgotPassword = ref(false)

// 验证码倒计时
const smsCodeTimer = ref(0)

// 添加图形验证码相关
const captchaUrl = ref('')

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  phone: '',
  smsCode: '',
  captcha: ''
})

// 注册表单
const registerForm = reactive({
  name: '',
  phone: '',
  email: '',
  password: '',
  confirmPassword: '',
  smsCode: '',
  captcha: ''
})

// 找回密码表单
const forgotPasswordForm = reactive({
  phone: '',
  smsCode: '',
  newPassword: '',
  confirmPassword: '',
  captcha: ''
})

// 表单验证规则
const loginRules = reactive<FormRules>({
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    // { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ]
})

const registerRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [         // 添加邮箱验证规则
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    // { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ]
})

const forgotPasswordRules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    // { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== forgotPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  captcha: [
    { required: true, message: '请输入图形验证码', trigger: 'blur' }
  ]
})

// 发送验证码
const handleSendSmsCode = async (type: 'login' | 'register' | 'forgot') => {
  let phone = ''
  let captcha = ''
  
  switch (type) {
    case 'login':
      phone = loginForm.phone
      captcha = loginForm.captcha
      break
    case 'register':
      phone = registerForm.phone
      captcha = registerForm.captcha
      break
    case 'forgot':
      phone = forgotPasswordForm.phone
      captcha = forgotPasswordForm.captcha
      break
  }

  if (!phone) {
    ElMessage.warning('请先输入手机号')
    return
  }

  if (!captcha) {
    ElMessage.warning('请先输入图形验证码')
    return
  }

  if (!/^1[3-9]\d{9}$/.test(phone)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }

  try {
    const data: SendSmsCodeRequest = {
      phone,
      captcha
    }
    
    console.log('发送验证码请求数据:', data)
    const response = await sendCode(data)
    console.log('发送验证码响应数据:', response)
    
    // 开始倒计时
    smsCodeTimer.value = 60
    const timer = setInterval(() => {
      smsCodeTimer.value--
      if (smsCodeTimer.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
    ElMessage.success('验证码发送成功')
  } catch (error: any) {
    console.log('错误详情:', {
      error,
      config: error.config,
      response: error.response,
      message: error.message,
      stack: error.stack
    })
    
    // 如果是空响应但状态码是200，说明发送成功
    if (!error.response && error.message === '请求失败' && error.config?.status === 200) {
      // 开始倒计时
      smsCodeTimer.value = 60
      const timer = setInterval(() => {
        smsCodeTimer.value--
        if (smsCodeTimer.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
      
      ElMessage.success('验证码发送成功')
      return
    }

    ElMessage.error(error.response?.data?.message || error.message || '发送验证码失败')
    // 刷新图形验证码
    refreshCaptcha()
  }
}

// 登录处理
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    loading.value = true
    
    const loginData: LoginRequest = loginType.value === 'account' 
      ? {
          loginType: 'account',
          phone: loginForm.phone,
          password: loginForm.password,
          captcha: loginForm.captcha
        }
      : {
          loginType: 'phone',
          phone: loginForm.phone,
          code: loginForm.smsCode,
          captcha: loginForm.captcha
        }
    
    const res = await login(loginData)
    console.log('登录响应数据:', res.data)
    // 直接使用返回的数据作为 token
    localStorage.setItem('token', res.data.toString())
        
    ElMessage.success('登录成功')
    // 登录成功后跳转到首页
    router.push('/home')
  } catch (error: any) {
    console.error('登录失败:', error)
    ElMessage.error(error.response?.data?.msg || '登录失败')
    if (loginType.value === 'account') {
      refreshCaptcha()
    }
  } finally {
    loading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return

  try {
    // 1. 表单验证
    await registerFormRef.value.validate()
    loading.value = true

    // 2. 构造注册数据
    const registerData: RegisterRequest = {
      name: registerForm.name,
      phone: registerForm.phone,
      email: registerForm.email,
      password: registerForm.password,
      code: registerForm.smsCode,
      captcha: registerForm.captcha
    }

    console.log('注册请求数据:', registerData)
    const response = await register(registerData)
    console.log('注册响应数据:', response)

    // 只要请求成功就认为注册成功
    ElMessage.success('注册成功，请登录')
    
    // 重置表单数据
    registerForm.name = ''
    registerForm.phone = ''
    registerForm.email = ''
    registerForm.password = ''
    registerForm.confirmPassword = ''
    registerForm.smsCode = ''
    registerForm.captcha = ''
    
    // 切换到登录页面
    switchToLogin()
  } catch (error: any) {
    console.error('注册失败:', error)
    ElMessage.error(error.response?.data?.msg || '注册失败，请重试')
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

// 重置密码处理
const handleResetPassword = async () => {
  if (!forgotPasswordFormRef.value) return

  try {
    await forgotPasswordFormRef.value.validate()
    loading.value = true

    const resetData: ResetPasswordRequest = {
      phone: forgotPasswordForm.phone,
      code: forgotPasswordForm.smsCode,
      newPassword: forgotPasswordForm.newPassword
    }
    console.log('重置密码请求数据:', resetData)
    
    await resetPassword(resetData)
    ElMessage.success('密码重置成功')
    // 重置表单
    forgotPasswordForm.phone = ''
    forgotPasswordForm.smsCode = ''
    forgotPasswordForm.newPassword = ''
    forgotPasswordForm.confirmPassword = ''
    // 切换到登录页面
    switchToLogin()
  } catch (error: any) {
    console.error('重置密码失败:', error)
    ElMessage.error(error.response?.data?.message || '重置密码失败')
  } finally {
    loading.value = false
  }
}

// 切换表单显示
const switchToLogin = () => {
  isRegister.value = false
  isForgotPassword.value = false
  // 重置表单
  if (loginFormRef.value) {
    loginFormRef.value.resetFields()
  }
}

const switchToRegister = () => {
  isRegister.value = true
  isForgotPassword.value = false
  // 重置表单
  if (registerFormRef.value) {
    registerFormRef.value.resetFields()
  }
}

const switchToForgotPassword = () => {
  isRegister.value = false
  isForgotPassword.value = true
  // 重置表单
  if (forgotPasswordFormRef.value) {
    forgotPasswordFormRef.value.resetFields()
  }
}

// 修改 2 函数
const refreshCaptcha = () => {
  // 直接更新验证码URL
  captchaUrl.value = getCaptcha()
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<style scoped>
.login-page {
  width: 100vw;
  height: 100vh; /* 确保容器占满整个页面高度 */
  display: flex; /* 启用 Flexbox 布局 */
  justify-content: center; /* 水平居中对齐子元素 */
  align-items: center; /* 垂直居中对齐子元素 */
  /* background-image: url('@/assets/login_background.png'); 背景图片路径 */
  background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('@/assets/login_background.png');
  background-size: cover; /* 让背景图片覆盖整个页面 */
  background-position: center; /* 背景图片居中 */
  background-repeat: no-repeat; /* 防止背景图片重复 */
  background-attachment: fixed; /* 背景图片固定在视口中 */
  
}

.login-container {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
/* background-color: #f5f7fa; */
}

.login-card {
width: 400px;
padding: 20px;
}

.card-header {
text-align: center;
font-size: 20px;
}

.captcha-image {
height: 40px;
margin-left: 10px;
cursor: pointer;
}

.login-btn {
width: 100%;
}

.forgot-password, .register {
text-align: center;
margin-top: 10px;
color: #409eff;
cursor: pointer;
}

.forgot-password:hover, .register:hover {
text-decoration: underline;
}

.form-footer {
display: flex;
justify-content: space-between;
margin-top: 20px;
}

:deep(.el-radio-group) {
width: 100%;
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}

:deep(.el-radio-button) {
flex: 1;
}

:deep(.el-radio-button__inner) {
width: 100%;
}
</style>
  